// gmfromfile.cpp : contains the function for loading gamemonkey scripts from a file
//$Id: gmFromFile.cpp 20 2009-08-16 05:51:41Z brwarner2 $
#include "stdafx.h"
#include "GameMonkey.h"

std::string Preprocess( const std::string& filename )
{
	//Open the file
	std::ifstream file(filename.c_str());
	if(!file) return "";

	//Read its contents and close the file
	std::string fileString = std::string( std::istreambuf_iterator<char>(file),
		std::istreambuf_iterator<char>());
	file.close();

	using namespace boost::filesystem;

	//Get the working directory of the script
	path cwd = path(filename).remove_filename();

	//Find each instance of #include>
	std::string::size_type pos = fileString.find("#include>");
	while( pos != std::string::npos )
	{
		//Read until the next line to get the filename
		std::string::size_type nl = fileString.find_first_of('\n', pos);
		std::string filename = fileString.substr(pos+9, nl-(pos+9));

		//Erase the include statement
		fileString.erase(pos, nl-pos);

		//Insert the file contents
		fileString.insert(pos, Preprocess( ( cwd / filename).string() ));

		//Find the next include statement
		pos = fileString.find("#include>");
	}
	return fileString;
}

int FromFile( gmMachine &a_machine, const char *filename )
{
	//Execute the file
	int ret = a_machine.ExecuteString(Preprocess(filename).c_str());

	//If there was a problem, print errors
	if( ret != 0 ) PrintErrorLog(a_machine);
	return ret;
}